<template>
  <el-dialog v-dialog-drag append-to-body :close-on-click-modal="false" width="800px" :visible.sync="visible"
    :before-close="beforeClose" :title="title">
    <div class="wrapper">
      <el-form ref="form" :rules="operateType.indexOf('View') > -1 ? {} : rules" :model="reviseForm" label-width="100px">
        <el-form-item label="成因" prop="questionOrigin">
          <el-input type="textarea" :rows="4" v-model="reviseForm.questionOrigin" placeholder="请输入成因"
            :disabled="operateType.indexOf('View') > -1"></el-input>
        </el-form-item>
      </el-form>
      <div v-for="(item, index) in reviseList" :key="index">
        <el-divider direction="horizontal" content-position="left">整改信息</el-divider>
        <ReviseForm ref="reviseForm" :operateType="operateType == 'reviseView' ? 'view' : operateType"
          :subpackageUnitIdsOptions="subpackageUnitIdsOptions" :form="item" />
        <div style="text-align: center;margin-bottom: 10px;">
          <el-button type="danger" size="mini" @click="deleteRevise(index)"
            v-if="operateType == 'revise' && reviseList.length > 1">删除</el-button>
        </div>
      </div>
      <div style="padding-left: 10px;">
        <el-button type="primary" size="mini" @click="addRevise" v-if="operateType == 'revise'">添加</el-button>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" @click="submit" v-if="operateType.indexOf('View') == -1">确定</el-button>
      <el-button size="mini" @click="beforeClose">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import ReviseForm from "./reviseForm";
import { doRevise, getSubUnits, getReviseDetail } from "../api";
function cloneObj(obj) {
  return JSON.parse(JSON.stringify(obj))
}
function required() {
  return { required: true, message: "此项不能为空", trigger: "change" }
}
export default {
  name: "ReviseReviewDialog",
  props: {
    visible: Boolean,
    title: {
      type: String,
      default: "任务整改"
    },
    data: {
      type: Object,
      default: () => { }
    },
    operateType: {
      type: String,
      default: "revise"
    },
  },
  components: { ReviseForm },
  data() {
    return {
      projectId: this.$store.state.app.selectData,
      subpackageUnitIdsOptions: [],
      reviseList: [],
      recordId: "",
      form: {
        recordId: '',
        id: "",
        operatorStatus: "1",
        subpackageUnitIds: "",
        operatorExplain: "",
        operatorPhoto: "",
        pics: [],
        isFine: "0",
        fineMoney: null,
        fineExplain: "",
      },
      reviseForm: {
        questionOrigin: "",
      },
      rules: {
        questionOrigin: [required()],
      },
    };
  },
  created() {
    this.initData();
  },
  methods: {
    async initData() {
      this.recordId = this.data.id;
      this.form.recordId = this.data.id;
      const res = await getSubUnits();
      this.subpackageUnitIdsOptions = res.rows;
      if (this.operateType.indexOf("View") > -1) {
        const detailRes = await getReviseDetail({recordId: this.data.recordId, id: this.data.id}); // todo pics处理
        this.reviseList = detailRes.data.listBizRectifyReview.map(item => ({
          ...item,
          pics: item.operatorPhotos.map(item => process.env.VUE_APP_MINIO_BASE_API+ '/'+ item.bucket + "/" + item.name)
        }))
        this.reviseForm.questionOrigin = detailRes.data.questionOrigin
      } else if (this.operateType == 'revise') {
        this.addRevise()
      }
    },
    beforeClose() {
      this.$emit('update:visible', false);
    },
    addRevise() {
      const clone = cloneObj(this.form)
      clone.projectId = this.projectId;
      this.reviseList.push(clone)
    },
    deleteRevise(index) {
      this.reviseList.splice(index, 1)
    },
    async submit() {
      let subpackageUnitIdsArray = []
      this.reviseList.forEach(item => {
        if (item.subpackageUnitIds) {
          subpackageUnitIdsArray.push(item.subpackageUnitIds)
        }
      })
      if (new Set(subpackageUnitIdsArray).size !== subpackageUnitIdsArray.length) {
        return this.$message.warning("分包单位重复，请仔细核对~")
      }
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return;
        }
        const forms = this.$refs.reviseForm
        const ress = await Promise.all(forms.map(item => item.validate()))
        const hasFail = ress.some(item => item == false)
        if (hasFail) {
          return;
        }

        const imageUploadRef = this.$refs.reviseForm;
        const list = imageUploadRef.map(item => item.pic())
        let data = {
          questionOrigin: this.reviseForm.questionOrigin,
          listBizRectifyReview: this.reviseList.map(item => ({ ...item, pics: null, recordId: this.recordId, projectId: this.projectId, operatorType: '2' }))
        }
        for (let i = 0; i < data.listBizRectifyReview.length; i++) {
          data.listBizRectifyReview[i].operatorPhoto = list[i]              
        }
        const res = await doRevise(data)
        if (res.code == 200) {
          this.$emit("refresh")
          this.beforeClose()
        }
      })
    },
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  max-height: 500px;
  overflow-y: auto;
  overflow-x: hidden;

  .el-select {
    width: 100%;
  }

  .el-date-editor {
    width: 100%;
  }
}
</style>
